package controllers

import (
	"crypto/tls"
	"fmt"
	"library/common"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
)

const (
	// oa 登录
	LOGIN_URL = "api/login"

	// oa 检查token并返回用户信息
	CHECK_TOKEN_URL = "api/check"
)

type UserInfo struct {
	UserName     string
	Departmentid string
}

// OA 的用户信息, 用户名为汉字,在uwork中不可用,用的是花名拼音
type UserData struct {
	Email        string `json:"email"`
	Departmentid string `json:"departmentid"`
}

type UserResp struct {
	Status   int      `json:"status"`
	UserData UserData `json:"data"`
}

type BaseRouter struct {
	beego.Controller
	IsLogin  bool
	Token    string
	UserUserId   int64
	UserUsername string
}


func (c *BaseRouter) Prepare() {
	userLogin, userAuth := c.GetUserNameFromOA()

	if userLogin == "" {
		c.IsLogin = false
	} else {
		c.IsLogin = true
		c.UserUsername = userLogin

		c.Data["Auth"] = userAuth
		c.Data["User"] = userLogin
	}
	c.Data["IsLogin"] = c.IsLogin
}

func (c *BaseRouter) GetUserNameFromOA() (string, string) {
	userName := c.GetSession("fe_UserName")
	actor := c.GetSession("userAuth")
	oaAuthWeb := beego.AppConfig.String("oa_auth_web")

	if userName == nil {
		// 获取user token
		tokenValue := c.GetString("token")
		if tokenValue == "" {
			loginUrl := oaAuthWeb + LOGIN_URL + "?jump_url=" + c.Ctx.Input.Site() + c.Ctx.Input.URI()
			beego.Info("PC OA login url: ", loginUrl)
			c.Redirect(loginUrl, 302)
			c.StopRun()
		}

		// 用token向OA获取用户信息
		userInfo, err := getUserInfo(tokenValue)
		if err != nil {
			beego.Error("Get user info err: ", err)
			loginUrl := oaAuthWeb + LOGIN_URL + "?jump_url=" + c.Ctx.Input.Site() + c.Ctx.Input.URI()
			c.Redirect(loginUrl, 302)
			c.StopRun()
		}

		userName = userInfo.UserName
		c.SetSession("fe_UserName", userInfo.UserName)
		c.SetSession("fe_Teamids", userInfo.Departmentid)
	}

	return common.GetString(userName), common.GetString(actor)
}

// 用token向 OA请求获取用户信息
func getUserInfo(tokenValue string) (*UserInfo, error) {
	var err error = nil
	oaAuthIp := beego.AppConfig.String("oa_auth_web")

	getUserInfoUrl := oaAuthIp + CHECK_TOKEN_URL + "?token=" + tokenValue
	beego.Info("getUserInfoUrl: ", getUserInfoUrl)

	userResp := UserResp{}

	req := httplib.Get(getUserInfoUrl)
	req.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	req.SetTimeout(8*time.Second, 8*time.Second)

	reqStr, _ := req.String()
	beego.Info("reqStr: ", reqStr)

	err = req.ToJSON(&userResp)
	if err != nil {
		beego.Error("Send OA check token err: ", err)
		return nil, err
	}

	beego.Info("userResp: ", userResp)

	emailIndex := strings.Index(userResp.UserData.Email, "@")
	if emailIndex < 0 {
		return nil, fmt.Errorf("user email is err")
	}

	userInfo := UserInfo{}
	userInfo.UserName = userResp.UserData.Email[:emailIndex]
	userInfo.Departmentid = userResp.UserData.Departmentid

	beego.Info("userInfo: ", userInfo)

	return &userInfo, nil
}